"use strict";



var box = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64];
var keystr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'm', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'N', 'M', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'S', 'Y', 'Z']

class Rc4 {
    constructor() {}

    getKsa(keys) {
        var length = keys.length
        var tmp
        var s = box.slice()
        var j = 0
        for (var i = 0; i < 64; i++) {
            j = (j + s[i] + keys[i % length]) % 64
            tmp = s[i]
            s[i] = s[j]
            s[j] = tmp
        }
        return s
    }

    encodeStr(str) {
        var buff = new Buffer(str)
        var key = ''
        for (var i = 0; i < 4; i++) {
            key += keystr[Math.floor(Math.random() * 62)]
        }
        var keys = new Buffer(key)
        var s = this.getKsa(keys)
        var dataBuff = this.body(buff, s)
        var encode = new Buffer(4 + dataBuff.length)
        keys.copy(encode, 0, 0, 4)
        dataBuff.copy(encode, 4)
        return encode
    }

    decodeBuffer(buff) {
        var keys = buff.slice(0, 4)
        var dataBuff = buff.slice(4)
        var s = this.getKsa(keys)
        var data = this.body(dataBuff, s)
        return data.toString()
    }

    body(buff, s) {
        var i = 0,
            j = 0,
            t = 0,
            tmp,
            len = buff.length
        for (var k = 0; k < len; k++) {
            i = (i + 1) % 64
            j = (j + s[i]) % 64
            tmp = s[i]
            s[i] = s[j]
            s[j] = tmp
            t = (s[i] + s[j]) % 64
            t = k % 64
            buff[k] ^= s[t]
        }
        return buff
    }
}
let rc4 = new Rc4()
module.exports = rc4
